'use strict';

/* Controllers */

var Auth = angular.module('services',[]);
Auth.factory('Login',function(){
	var verify = {};
	verify.user = 'guest';
	verify.isLogged = false;

	verify.logIn = function(username,password){
		verify.user = username;
		verify.isLogged = true;
		return verify;
	}
	verify.logOut = function(){
		verify.user = 'guest';
		verify.isLogged = false;
		return verify;
	}

	return verify;
});

var controllers=angular.module('controllers',['services','ngCookies']);

function ProfileCtrl($scope, $rootScope, $http) {
  $http.get('artData/Sprint2.json').success(
	function(data){
		var parameter=location.search;
		var x=parameter.split(";");
		parameter=x[0].substring(10);
		
		$rootScope.artwork = data.Artwork;
		$rootScope.film = data.Film;
		$rootScope.series=data.Series;
		$rootScope.music=data.Music;
		$rootScope.performance=data.Performance;
		$rootScope.artists = data.Artist;
		$scope.artistNum=parseInt(parameter);
		$scope.currentUser = "guest"
		
        $scope.loggedIn = false;
        $scope.submit = function() {
		    if(this.username){
		        $scope.artists.push({"artistID" : artists.length, "username": $this.username, "headline" : "", 
				"bio" : "", "state" : "", 
				"thumbnail" : "", "city" : "", "followers" : 0, "following" : 0});
			}
	  	};
        $scope.logon = function(username,password){
        	$scope.loggedIn = true;
        	for(var i = 0; i<$rootScope.artists.length;i++){
        		if($rootScope.artists[i].username == username){
        			if($rootScope.artists[i].city == password){
  						$scope.loggedIn = true;
  						$scope.currentUser = username;
  					}
  				}	

        	} 
        }

		$scope.title = 'Type your title HERE';
		$scope.description = 'Type your description HERE';
		$scope.category = "Visual Art";
		$scope.subcategory = "Sculpture";
		$scope.shouldUpload = false;
		$scope.shouldUpdate = false;
  		$scope.word = /^\s*\w*\s*$/;
  		$scope.updateSubcategory = function() {
  			
  		}
  		
		$scope.clearClickTitle = function() {
			if(this.title){
				this.title = "";
			}
		}
		$scope.clearClickDescript = function() {
		  	if(this.description){
		  		this.description = "";
		  	}
		}	

  		$scope.submit = function() {
   	 		if (this.title && this.description) {
        		$scope.artwork.push({ "artID" : this.nextArtID, "subcategory" : this.subcategory, "title" : this.title, "description" : this.description, 
			"thumbnail" : "img/art/" + this.nextArtID + ".jpg", "days" : 0, "category" : this.category, "artistID" : this.artistNum, 
			"featured" : -1, "Rating" : 0, "View" : 0 });
        		this.title = '';
        		this.description = '';
    		}
  		};
		
		$scope.submitUpdate = function() {}
		
		//check to see if value read from url is valid
		if(isNaN($scope.artistNum))
			$scope.artistNum=0;
		
		var array=[];
		
		for(var i=0; i<$scope.artwork.length; i++)
		{
			if($rootScope.artists[$scope.artistNum].artistID==$scope.artwork[i].artistID)
			{
				array.push($scope.artwork[i].artID);	
			}
		}
		
		$rootScope.artistArt=array;
		$rootScope.artistArtLength=array.length;
		}
		
	);
	
	$scope.setFiles = function(element) {
    $scope.$apply(function() {
      //console.log('files:', element.files);
      // Turn the FileList object into an Array
    	$scope.files = [];
        for (var i = 0; i < element.files.length; i++) {
          $scope.files.push(element.files[i]);
        }
      $scope.progressVisible = false;
      });
    };

    $scope.uploadFile = function() {
        var fd = new FormData();
        for (var i in scope.files) {
            fd.append("uploadedFile", scope.files[i]);
        }
        //XML to upload files
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener("progress", uploadProgress, false);
        xhr.addEventListener("load", uploadComplete, false);
        xhr.addEventListener("error", uploadFailed, false);
        xhr.addEventListener("abort", uploadCanceled, false);
        xhr.open("POST", "/fileupload");
        $scope.progressVisible = true;
        xhr.send(fd);
    }

    function uploadProgress(evt) {
        $scope.$apply(function(){
            if (evt.lengthComputable) {
                $scope.progress = Math.round(evt.loaded * 100 / evt.total);
            } else {
                $scope.progress = 'unable to compute';
            }
        })
    }

    function uploadComplete(evt) {
        /* This event is raised when the server send back a response */
        alert(evt.target.responseText);
    }

    function uploadFailed(evt) {
        alert("There was an error attempting to upload the file.");
    }

    function uploadCanceled(evt) {
        $scope.$apply(function(){
            $scope.progressVisible = false;
        })
        alert("The upload has been canceled by the user or the browser dropped the connection.");
    }
}

function CarouselCtrl($scope){
	var slides = $scope.slides = [{'image':'pictures/Fennekin.png','name':'Fennekin','text':'Fire starter'},
	{'image':'pictures/Malamar.png','name':'Malamar','text':'Demon squid'},{'image':'pictures/Tyrantrum.png','name':'Tyrantrum','text':'Rocky tyranno'},
	{'image':'pictures/Yveltal.png','name':'Yveltal','text':'Utra bird'}
	];
}

function ArtPageCtrl($scope, $rootScope, $http, $location) {
  $http.get('artData/Sprint2.json').success(
	function(data){
		
		//read from url
		var parameter=location.search;
		var x=parameter.split(";");;
		parameter=x[0].substring(7);
		$rootScope.artType=0; //will be calculated
		$rootScope.visualArt=data.Artwork;
		$rootScope.artwork = data.Artwork;//Current category of art shown
		$rootScope.film = data.Film;
		$rootScope.music = data.Music;
		$rootScope.performance = data.Performance;
		$rootScope.series = data.Series;
		$rootScope.artists = data.Artist;
		$rootScope.comments=data.Comments;
		$scope.artNum=parseInt(parameter);
		
		//check to see if value read from url is valid
		if(isNaN($scope.artNum))
			$scope.artNum=0;
		
		$scope.artistNum=0; //Automatically Calculated
		$scope.artRating=14;
		
		
		
		var array2=[];
		//Comments for current artwork calculation
		for(var i=0; i<$scope.comments.length; i++)
		{
			if($scope.comments[i].artID==$scope.artNum)
			{	
				array2.push($scope.comments[i].commentID);	
			}
		}
		$rootScope.commentList=array2;
		$rootScope.commentListLength=array2.length;
		
		//arttype calculation
		switch (x[1].substring(9))
		{
			case "visualArt":
				$rootScope.artType=0;
				$rootScope.artwork = data.Artwork;
				break;
			case "film":
				$rootScope.artType=1; 
				$rootScope.artwork = data.Film;
				break;
			case "performance":
				$rootScope.artType=2; 
				$rootScope.artwork = data.Performance;
				break;
			case "series":
				$rootScope.artType=3; 
				$rootScope.artwork = data.Series;
				break;
			case "music":
				$rootScope.artType=4; 
				$rootScope.artwork = data.Music;
				break;
			default: 
				$rootScope.artType=0; 
				$rootScope.artwork = data.Artwork;
				break;
		}
		//artistNum Calculation
		var array=$scope.artwork;
		for(var i=0; i<array.length; i++)
		{
			if(array[i].artID==$scope.artNum)
			{
				$scope.artistNum=array[i].artistID;
			}
		}
		//console.log(artType);
	}
	);
}
function UserCtrl($scope, $rootScope, $http, $location,$cookieStore,Login){
  $http.get('artData/Sprint2.json').success(
	function(data){
		var logged = $scope.logged = {};
		$rootScope.artists = data.Artist;
		var parameter=location.search;
		$scope.loggedIn=false;
		$scope.curUser=0;
		var x=parameter.split(";");
		if(!$cookieStore.get('log')){
			var auth = $scope.auth = Login;
		}
		else{
			var auth = $scope.auth = $cookieStore.get('log');
		}
		$scope.logon = function(){
			var check = $http({
       			 method  : 'POST',
       			 url     : 'test.php',
        		data    : $.param({logged:logged,logName:logged.username,logPassword:logged.password}),  // pass in data as strings
       			 headers : { 'Content-Type': 'application/x-www-form-urlencoded'}  // set the headers so angular passing info as form data (not request payload)
    	}).
        success(function(data) {
            $scope.data = data;
            console.log($scope.data);
			if($scope.data==1){
				console.log(data);
				Login.logIn(logged.username,logged.password);
				$cookieStore.put('log',Login);
				location.reload();
			}	
        });
			
		}
		$scope.logout = function(){
			Login.logOut();
			$cookieStore.put('log',Login);
			location.reload();
		}

		if(x[2]!=null)
		{
			//TODO: Implement checking to see if it actually is that user.
			var user=x[2].substring(5);
			$scope.curUser=parseInt(user);
			$scope.loggedIn=true;
			if(isNaN($scope.curUser))
			{
				$scope.curUser=0;
				$scope.loggedIn=false;
			}
		}
		else
		{
			$scope.loggedIn=false;
		}
		//$scope.loggedIn=true;
		//$scope.curUser=4;
	}
   );
}
function SignUpFormCtrl($scope,$http){
	var user = $scope.user = {};
	$scope.processForm = function() {
	$http({
        method  : 'POST',
        url     : 'test.php',
        data    : $.param({user:user,username:user.username,name:user.name,password:user.password}),  // pass in data as strings
        headers : { 'Content-Type': 'application/x-www-form-urlencoded'}  // set the headers so angular passing info as form data (not request payload)
    })
        .success(function(data) {
            console.log(data);
        });
};
}


function ArtCtrl($scope, $http, $filter) {
  $http.get('sprint2.json').success(
	function(data){
		$scope.artwork = data;
		$scope.currArt = $scope.artwork[0];
	}
	
   );
	$scope.display;
	$scope.displayChange = function(string){
		$scope.display = string;
	};
	$scope.sort = 'days';
	$scope.ascend = 'true';
	$scope.fields = ['all','title','artist','subcategory'];
    $scope.select = $scope.fields[0];
	$scope.filterman = {};
	$scope.$watch(function () {
        return [$scope.searchField, $scope.search];
    }, function () {
        $scope.filterman = {};
        if ($scope.search && $scope.searchField) {
            $scope.filterman[$scope.searchField] = $scope.search;
        }
    });

}

function ArtistCtrl($scope, $http) {
  $http.get('artists.json').success(
	function(data){
		$scope.artists = data;
		$scope.currArtist = $scope.artists[0].name;
	}
   );

}


